package com.wzq.upms.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 文件帮助类
 * 
 * project：pub-core
 * 
 * $Author:Jeffy Chen
 * @version $Revision:$ 
 * @Modify $Date:$
 * @create time：2014-4-26 下午11:02:47
 *
 */
public class FileHelper {
	
	private static Logger logger = LogManager.getLogger(FileHelper.class);
	
	// 对于encodingFilter中的字符集，都替换成系统默认字符集GBK
	/*private static List<String> encodingFilter = Arrays.asList(new String[] {
			"GB18030", "BIG5", "ISO-8859-8", "WINDOWS-1252", "IBM866"
	});*/
	
	/**
	 * 读文件
	 */
	public static String readFile(String file) {
		return readFile(new File(file));
	}
	
	public static String readFile(File file) {
		try {
			return FileUtils.readFileToString(file);
		} catch (Exception e) {
			return "";
		}
	}
	
	/**
	 * 写文件
	 */
	public static boolean writeFile(String file, String content, String charsetName) {
		return writeFile(new File(file), content, charsetName);
	}
	
	public static boolean writeFile(File file, String content, String charsetName) {
		try {
			FileUtils.write(file, content, charsetName);
			return true;
		} catch (Exception e) {
			logger.error("写文件" + file + "失败: ", e);
			return false;
		}
	}
	
	/**
	 * 复制文件
	 */
	public static void copyFile(InputStream in, OutputStream out) {
		try {
			IOUtils.copy(in, out);
		} catch (Exception e) {
			logger.error("复制文件失败: ", e);
		}
	}
	
	public static boolean copyFile(File from, File to) {
		try {
			FileUtils.copyFile(from, to);
			return true;
		} catch (Exception e) {
			logger.error("复制文件失败: ", e);
			return false;
		}
	}
	
	/**
	 * 获取文件md5值
	 */
	public static String getFileMD5(String file) {
        try{
	    	MessageDigest md = MessageDigest.getInstance("MD5");
	        FileInputStream in = new FileInputStream(file);
	        byte[] buffer = new byte[1024 * 4];
	        int length = -1;
	        while ((length = in.read(buffer)) != -1) {
	            md.update(buffer, 0, length);
	        }
	        in.close();
	        return bytesToString(md.digest()).toUpperCase();
        } catch (Exception e) {
        	logger.error("获取文件md5值失败: ", e);
			return "";
		}
    }
	
	private static String bytesToString(byte[] data) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] temp = new char[data.length * 2];
        for (int i = 0; i < data.length; i++) {
            byte b = data[i];
            temp[i * 2] = hexDigits[b >>> 4 & 0x0f];
            temp[i * 2 + 1] = hexDigits[b & 0x0f];
        }
        return new String(temp);
    }
	
	/*
	private static int countMatches(String str, String sub) {
		if ((str == null || str.equals(""))
				|| (sub == null || sub.equals(""))) {
			return 0;
		}
		int count = 0;
		int idx = 0;
		while ((idx = str.indexOf(sub, idx)) != -1) {
			count++;
			idx += sub.length();
		}
		return count;
	}*/
	
	
	/**
	 * 分割文件，将文件按partSize的大小进行分割
	 * @param fileName 文件名
	 * @param partSize 1000 * 1024 为1M
	 */
	public static void splitter(String fileName, int partSize) {
		File file = new File(fileName);
		FileInputStream fis = null;
		byte[] buf = new byte[1024];
		int byteRead = 0, byteToWrite = 0;

		try {
			fis = new FileInputStream(file);
			long fileLength = file.length();
			long fileCount = (fileLength % partSize == 0) ? (fileLength / partSize) : (1 + fileLength / partSize);

			long num = 1;
			while (true) {
				String partFileName = fileName + ".part" + getPartNum(fileCount, num++);
				FileOutputStream fos = new FileOutputStream(new File(partFileName));
				if (byteToWrite < byteRead) {
					int byteLeft = byteRead - byteToWrite;
					fos.write(buf, byteToWrite, byteLeft);
				}

				int byteWrited = 0;
				while (byteWrited < partSize) {
					byteRead = fis.read(buf);
					if (byteRead <= 0)
						break;

					byteToWrite = byteRead < (partSize - byteWrited) ? byteRead : (partSize - byteWrited);
					fos.write(buf, 0, byteToWrite);
					byteWrited += byteToWrite;
				}
				fos.close();
				if (byteRead <= 0) {
					fis.close();
					break;
				}
			}
		} catch (IOException e) {
			logger.error("关闭文件流失败: ", e);
			return;
		}
	}
	
	private static String getPartNum(long total, long x) {
		String prefix = "";
		while (Long.toString(total).length() > Long.toString(x).length()) {
			total /= 10;
			prefix += "0";
		}

		return prefix + Long.toString(x);
	}
	
	/**
	 * 得到文件扩展名
	 * @param fileName
	 * @return
	 */
	public static String getFileExtension(String fileName) {
		int i = fileName.lastIndexOf(".");
		if (i >= 0) {
			return fileName.substring(i + 1, fileName.length());
		}
		return "";
	}
	
}
